package com.fenfen.novel;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import com.afollestad.materialdialogs.folderselector.FolderChooserDialog;
import com.fenfen.novel.fragment.SettingFragment;
import com.fenfen.novel.utils.SharedPrefsUtils;

import net.xpece.android.support.preference.ColorPreference;
import net.xpece.android.support.preference.XpColorPreferenceDialogFragment;

import java.io.File;

public class SettingActivity extends BaseActivity implements PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback, FolderChooserDialog.FolderCallback {

  private SettingFragment fragment;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setting);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
      toolbar.setTitle(R.string.title_activity_setting);
      setSupportActionBar(toolbar);

      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    if (savedInstanceState == null) {
      fragment = SettingFragment.newInstance(null);
      getSupportFragmentManager().beginTransaction().add(R.id.container, fragment, "Settings").commit();
    } else {
      fragment = (SettingFragment) getSupportFragmentManager().findFragmentByTag("Settings");
    }
  }

  @Override
  public boolean onOptionsItemSelected(final MenuItem item) {
    int id = item.getItemId();
    switch (id) {
      case android.R.id.home: {
        super.onBackPressed();
        return true;
      }
    }
    return super.onOptionsItemSelected(item);
  }

  @Override
  public boolean onPreferenceDisplayDialog(PreferenceFragmentCompat preferenceFragmentCompat, Preference preference) {
    final String key = preference.getKey();
    DialogFragment f;
    if (preference instanceof ColorPreference) {
      f = XpColorPreferenceDialogFragment.newInstance(key);
    } else {
      return false;
    }
    f.setTargetFragment(preferenceFragmentCompat, 0);
    f.show(this.getSupportFragmentManager(), key);
    return true;
  }

  @Override
  public void onFolderSelection(@NonNull FolderChooserDialog dialog, @NonNull File folder) {
    if (dialog.getTag().equals(SharedPrefsUtils.ShardPrefsKey.DOWNLOAD_DIR)) {
      SharedPrefsUtils.getInstance(this).setDownloadDir(folder.getAbsolutePath());
      fragment.callDownDirUpdate(folder.getAbsoluteFile());
    }
  }
}
